package com.hevery.warpper;

import javax.servlet.ServletOutputStream;
import javax.servlet.WriteListener;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.OutputStream;

/**
 * @Author: Hevery
 * @Description: 因为ServletResponse本身是Servlet流，所以ServletOutputStreamCopier要继承ServletOutputStream
 * @Date: Created on 2017/10/8
 * @Modified By:
 */
public class ServletOutputStreamCopier extends ServletOutputStream {
    private OutputStream outputStream;
    private ByteArrayOutputStream copy;

    /**将传入的Outputstream(实际上也就是ServletResponse)赋给outputStream，并且对拷贝的字节流进行初始化*/
    public ServletOutputStreamCopier(OutputStream outputStream) {
        this.outputStream = outputStream;
        this.copy = new ByteArrayOutputStream(1024);
    }

    /**此处是重点，字节流进行写回的同时，也将获得对应的一份拷贝*/
    @Override
    public void write(int b) throws IOException {
        outputStream.write(b);
        copy.write(b);
    }

    /**获得拷贝的ServletResponse转换为字节数组*/
    public byte[] getCopy() {
        return copy.toByteArray();
    }

    @Override
    public boolean isReady() {
        return false;
    }

    @Override
    public void setWriteListener(WriteListener writeListener) {

    }
}